<template>
  <div class="lawyer-container">
    <!-- 搜索区域保持不变 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item label="姓名">
          <el-input v-model="formInline.realname" style="width: 180px" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="formInline.idCard" style="width: 220px" placeholder="请输入身份证号" clearable />
        </el-form-item>
        <el-form-item label="执业证号">
          <el-input v-model="formInline.licenseNo" style="width: 200px" placeholder="请输入执业证号" clearable />
        </el-form-item>
        <el-form-item label="律师类型">
          <el-select v-model="formInline.lawyerType" style="width: 160px" placeholder="请选择律师类型" clearable>
            <el-option label="律师" value="律师" />
            <el-option label="兼职律师" value="兼职律师" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作状态">
          <el-select v-model="formInline.workStatus" style="width: 160px" placeholder="请选择工作状态" clearable>
            <el-option label="在职" value="在职" />
            <el-option label="离职" value="离职" />
            <el-option label="休假" value="休假" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 - 移除添加、编辑、删除按钮 -->
    <el-card>
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="lawyerId"
        style="width: 100%"
        size="small"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column property="realname" label="姓名" width="80" />
        <el-table-column property="sex" label="性别" width="60" align="center">
          <template #default="scope">
            {{ scope.row.sex === 'm' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column property="nation" label="民族" width="80" align="center" />
        <el-table-column property="education" label="学历" width="80" align="center"/>
        <el-table-column property="idCard" label="身份证号" width="180" align="center"/>
        <el-table-column property="phone" label="电话" width="120" align="center"/>
        <el-table-column property="licenseNo" label="执业证号" width="160" align="center"/>
        <el-table-column property="lawyerType" label="律师类型" width="100" align="center"/>
        <el-table-column property="workStatus" label="工作状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.workStatus === '在职' ? 'success' : 'warning'">
              {{ scope.row.workStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="hireDate" label="聘用日期" width="130" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.hireDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130" align="center">
          <template #default="scope">
            <el-button size="small" type="text" @click="openDetail(scope.row.lawyerId)">
              查看
            </el-button>
            <el-button size="small" type="text" class="delete-btn" @click="handleDelete(scope.row.lawyerId, scope.row.realname)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页保持不变 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right"
        size="small"
      />
    </el-card>

    <!-- 详情抽屉 - 保持与后端字段一致 -->
    <el-drawer v-model="detailVisible" title="律师详情" direction="rtl" size="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ detailData.realname || '--' }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ detailData.sex === 'm' ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="民族">{{ detailData.nation || '--' }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatDate(detailData.birthday) || '--' }}</el-descriptions-item>
        <el-descriptions-item label="政治面貌">{{ detailData.politicalStatus || '--' }}</el-descriptions-item>
        <el-descriptions-item label="入党时间">{{ formatDate(detailData.joinPartyDate) || '--' }}</el-descriptions-item>
        <el-descriptions-item label="现居住地">{{ detailData.residence || '--' }}</el-descriptions-item>

        <el-descriptions-item label="毕业院校">{{ detailData.graduateSchool || '--' }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ detailData.major || '--' }}</el-descriptions-item>
        <el-descriptions-item label="学历">{{ detailData.education || '--' }}</el-descriptions-item>

        <el-descriptions-item label="身份证号">{{ detailData.idCard || '--' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phone || '--' }}</el-descriptions-item>
        <el-descriptions-item label="业务邮箱">{{ detailData.email || '--' }}</el-descriptions-item>
        <el-descriptions-item label="执业证号">{{ detailData.licenseNo || '--' }}</el-descriptions-item>

        <el-descriptions-item label="取得职业资格日期">{{ formatDate(detailData.qualificationDate) || '--' }}</el-descriptions-item>
        <el-descriptions-item label="业务特长">{{ detailData.businessSpecialty || '--' }}</el-descriptions-item>
        <el-descriptions-item label="是否合伙人">{{ detailData.isPartner === 1 ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="是否担任人大代表或政协委员">{{ detailData.representative === 1 ? '是' : '否' }}</el-descriptions-item>

        <el-descriptions-item label="律师类型">{{ detailData.lawyerType || '--' }}</el-descriptions-item>
        <el-descriptions-item label="兼职工作单位">{{ detailData.partTimeWork || '--' }}</el-descriptions-item>
        <el-descriptions-item label="工作状态">
          <el-tag :type="detailData.workStatus === '在职' ? 'success' : 'warning'">
            {{ detailData.workStatus || '--' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="聘用日期">{{ formatDate(detailData.hireDate) || '--' }}</el-descriptions-item>

        <el-descriptions-item label="受过的奖励">{{ detailData.award || '--' }}</el-descriptions-item>
        <el-descriptions-item label="受过的处分">{{ detailData.punishment || '--' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remark || '--' }}</el-descriptions-item>

        <el-descriptions-item label="一寸照片">
          <el-image
            v-if="detailData.photo"
            :src="detailData.photoUrl"
            alt="照片"
            style="width: 150px; height: 200px;"
            fit="contain"
            @error="handleImageError"
          />
          <span v-else>--</span>
        </el-descriptions-item>
        <el-descriptions-item label="个人简历">
          <a
            v-if="detailData.resume"
            :href="getCertificateUrl(detailData.resume)"
            target="_blank"
            class="file-link"
          >
            查看简历
          </a>
          <span v-else>--</span>
        </el-descriptions-item>

        <el-descriptions-item label="首次社保缴费日期">{{ formatDate(detailData.firstSocialSecurityDate) || '--' }}</el-descriptions-item>
        <el-descriptions-item label="社保编号">{{ detailData.socialSecurityNo || '--' }}</el-descriptions-item>
        <el-descriptions-item label="社会职务">{{ detailData.socialDutie || '--' }}</el-descriptions-item>
        <el-descriptions-item label="学术成果">{{ detailData.academicAchievements || '--' }}</el-descriptions-item>
        <el-descriptions-item label="法律顾问单位">{{ detailData.legalAdvisorUnits || '--' }}</el-descriptions-item>

        <el-descriptions-item label="档案调转记录">
          <a
            v-if="detailData.fileTransferRecords"
            target="_blank"
            class="file-link"
            @click="downloadLawyerFile(detailData.fileTransferRecords)"
          >
            查看档案调转记录
          </a>
          <span v-else>--</span>
        </el-descriptions-item>

        <el-descriptions-item label="转所记录">
          <a
            v-if="detailData.transferRecords"
            @click="downloadLawyerFile(detailData.transferRecords)"
            target="_blank"
            class="file-link"
          >
            查看转所记录
          </a>
          <span v-else>--</span>
        </el-descriptions-item>

        <el-descriptions-item label="证书列表" :span="2">
          <div v-if="detailData.certificates?.length" class="certificate-list">
            <el-card
              v-for="(cert, index) in detailData.certificates"
              :key="index"
              class="certificate-item"
            >
              <div class="certificate-info">
                <span class="certificate-name">证书名称：{{ cert.certificateName }}</span>
                <el-button @click="downloadLawyerFile(cert.certificateUrl)">
                  下载证书
                </el-button>
              </div>
              <el-image
                v-if="cert.imageUrl"
                :src="cert.imageUrl"
                alt="证书预览"
                style="width: 100%; max-height: 300px; margin-top: 10px"
                fit="contain"
              />
            </el-card>
          </div>
          <span v-else>--</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {ElMessage, ElLoading, ElMessageBox} from 'element-plus'
import {getLawyers, getLawyerDetail, deleteLawyer} from '@/api/lawyer'
import {getFileUrl} from "@/api/file";


//一、 类型接口定义
// 证书接口类型定义
interface Certificate {
  id?: number;
  lawyerId?: number;
  certificateName: string;
  certificateUrl?: string;
  imageUrl?: string; // 新增：用于存储带Token的图片临时URL
}

// 律师信息接口类型，与后端LawyerQueryVo对应
interface Lawyer {
  lawyerId: number | string;
  realname: string;
  sex: string;
  nation: string;
  birthday: string;
  graduateSchool: string;
  major: string;
  education: string;
  politicalStatus: string;
  joinPartyDate: string;
  idCard: string;
  phone: string;
  email?: string;
  residence: string;
  licenseNo: string;
  qualificationDate: string;
  businessSpecialty: string;
  isPartner: number;
  hireDate: string;
  lawyerType: string;
  partTimeWork?: string;
  representative: number;
  award: string;
  punishment: string;
  workStatus: string;
  remark: string;
  photo: string;
  photoUrl?: string; // 带Token的临时URL
  resume: string;
  firstSocialSecurityDate: string;
  socialSecurityNo: string;
  socialDutie: string;
  academicAchievements: string;
  legalAdvisorUnits: string;
  fileTransferRecordsUrl: string;
  transferRecordsUrl: string;
  certificates?: Certificate[];
}

// 查询参数类型
interface LawyerQueryParams {
  realname?: string;
  idCard?: string;
  licenseNo?: string;
  lawyerType?: string;
  workStatus?: string;
  userId?: number | string;
  page: number;
  pageSize: number;
}


//二、响应式数据声明
// 详情相关
const detailVisible = ref(false)
const detailData = ref<Lawyer>({} as Lawyer)

// 表格相关
const tableData = reactive<Lawyer[]>([])
const loading = ref(false)

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单，与后端LawyerQueryDTO对应
const formInline = reactive({
  realname: '',
  idCard: '',
  licenseNo: '',
  lawyerType: '',
  workStatus: '',
  userId: undefined
})


//三、生命周期钩子函数
// 页面挂载时加载数据
onMounted(() => {
  getLawyersByCondition()
})


//四、工具函数
// 获取Token
const getToken = () => {
  return sessionStorage.getItem("token") || "";
};

//文件请求工具
const requestFile = async (fileName: string, responseType: 'blob' | 'text' = 'blob') => {
  if (!fileName || !getToken()) return null;

  try {
    const res = await fetch(
      getFileUrl(fileName),
      { headers: { 'Authorization': `Auth ${getToken()}` } }
    );

    if (!res.ok) throw new Error(`状态码: ${res.status}`);
    return responseType === 'blob' ? await res.blob() : await res.text();
  } catch (e) {
    ElMessage.error(`操作失败: ${(e as Error).message}`);
    return null;
  }
};

//图片加载函数
const getImageWithToken = async (fileName: string) => {
  const blob = await requestFile(fileName);
  return blob ? URL.createObjectURL(blob) : '';
};

//文件下载工具
const downloadLawyerFile = async (fileName: string) => {
  if (!fileName) {
    ElMessage.error('文件名不存在');
    return;
  }
  const blob = await requestFile(fileName);
  if (!blob) return;
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();

  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }, 100);
};

// 图片文件判断函数
const isImageFile = (fileName: string) => {
  if (!fileName) return false;
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
  const ext = fileName.split('.').pop()?.toLowerCase();
  return ext && imageExtensions.includes(ext);
};

// url生成
const getCertificateUrl = (fileName: string) => {
  return getFileUrl(fileName);
};

// 错误处理，图片加载失败处理
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  // 替换为国内可访问的占位图服务
  img.alt = '图片加载失败';
};

// 日期格式化函数
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '--';

  try {
    const date = new Date(dateString);

    if (isNaN(date.getTime())) {
      return '无效日期';
    }

    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    const pad = (num: number) => num.toString().padStart(2, '0');

    return `${year}年${pad(month)}月${pad(day)}日`;
  } catch (error) {
    console.error('日期格式化失败:', error);
    return '格式错误';
  }
};


//五、核心业务逻辑
// 详情弹窗逻辑 合并后的获取详情并打开弹窗函数
async function openDetail(id: number | string) {
  loading.value = true;
  try {
    const { data } = await getLawyerDetail(id);
    detailData.value = data;

    // 加载照片（用新字段存储临时URL，保留原始fileName）
    if (data.photo) {
      detailData.value.photoUrl = await getImageWithToken(data.photo);
    }

    // 加载证书图片
    data.certificates?.forEach(async (cert) => {
      if (cert.certificateUrl && isImageFile(cert.certificateUrl)) {
        cert.imageUrl = await getImageWithToken(cert.certificateUrl);
      }
    });

    detailVisible.value = true;
  } catch (e) {
    ElMessage.error('获取详情失败');
  } finally {
    loading.value = false;
  }
}

//删除功能
const handleDelete = (lawyerId: number | string, realaname: string) => {
  ElMessageBox.confirm(
    `确定要删除律师【${realaname}】吗？此操作不可恢复！`,
    '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }
  ).then(async () => {
    const loadingInstance = ElLoading.service({
      lock:true,
      text:'正在删除...',
      background:'rgba(0,0,0,0.7)'
    })

    try {
      //调用删除api，注意后端接收是数组形式
      await deleteLawyer([Number(lawyerId)]);
      ElMessage.success('删除成功');
      //重新加载数据
      getLawyersByCondition();
    } catch (error) {
      ElMessage.error(`删除失败：${(error as Error).message}`)
    }finally {
      loadingInstance.close();
    }
  })
    .catch(()=>{
      ElMessage.info('已取消删除')
    })
};

// 搜索功能
const onSubmit = () => {
  pagination.current = 1
  getLawyersByCondition()
}

//表单重置
function resetForm() {
  formInline.realname = ""
  formInline.idCard = ""
  formInline.licenseNo = ""
  formInline.lawyerType = ""
  formInline.workStatus = ""
  formInline.userId = undefined
  pagination.current = 1
  getLawyersByCondition()
}

// 表格数据加载 获取律师列表
function getLawyersByCondition() {
  loading.value = true
  const params = {
    ...formInline,
    page: pagination.current,
    pageSize: pagination.pageSize
  }
  getLawyers(params).then(res => {
    const { list, total } = res.data
    tableData.length = 0
    tableData.push(...list)
    pagination.total = total
  }).catch(error => {
    ElMessage.error('查询失败: ' + (error as Error).message)
  }).finally(() => {
    loading.value = false
  })
}

// 分页事件处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.current = 1
  getLawyersByCondition()
}
const handleCurrentChange = (val: number) => {
  pagination.current = val
  getLawyersByCondition()
}

</script>

<style scoped>
.lawyer-container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  padding: 20px;
}

.filter-card {
  margin-bottom: 15px;
}

.certificate-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 10px;
}

.certificate-item {
  width: 100%;
}

.certificate-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.certificate-name {
  font-weight: 500;
}


.delete-btn {
  color: #ff4d4f !important; /* 这里添加了 !important */
}

.delete-btn:hover {
  color: #f5222d !important; /* 这里也添加了 !important */
}

.file-link {
  color: #409eff;
  text-decoration: underline;
  cursor: pointer;
}
.file-link:hover {
  color: #66b1ff;
}
</style>
